package io.boot.modules.activiti.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.boot.common.utils.PageUtils;
import io.boot.common.utils.Query;
import io.boot.modules.activiti.dao.ActLeaveDao;
import io.boot.modules.activiti.entity.ActLeaveEntity;
import io.boot.modules.activiti.service.ActLeaveService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author kyson
 * @date 2020/04/17 11:52
 */
@Service("actLeaveService")
public class ActLeaveServiceImpl extends ServiceImpl<ActLeaveDao, ActLeaveEntity> implements ActLeaveService {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;


    @Override
    public PageUtils queryPage(Map<String, Object> params, Long userId) {
        IPage<ActLeaveEntity> page = this.page(
                new Query<ActLeaveEntity>().getPage(params),
                new QueryWrapper<ActLeaveEntity>()
                .in((List<Long>) params.get("list")!=null,"create_by",(List<Long>) params.get("list"))
                .orderByDesc("create_time")
        );
        List<ActLeaveEntity> list=page.getRecords();
        for (ActLeaveEntity actleave:list) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(actleave.getInstanceId()).singleResult();
            if(processInstance!=null) {
                actleave.setStatus(processInstance.isSuspended());
                List<Task> taskList = taskService.createTaskQuery().processInstanceId(actleave.getInstanceId()).list();
                List<String> nowTaskList = new ArrayList<>();
                for (Task tsk : taskList) {
                    nowTaskList.add(tsk.getName());
                }
                actleave.setNowTaskName(String.join(",", nowTaskList.toString()).replace("[", "").replace("]", ""));
            }else{
                actleave.setNowTaskName("已完结");
            }
        }
        return new PageUtils(page);
    }
}
